package com.justech.eat.service.impl;

import com.justech.common.util.DateUtil;
import com.justech.common.util.MesAssert;
import com.justech.eat.controller.req.OrderDetailReq;
import com.justech.eat.entity.Order;
import com.justech.eat.entity.OrderDetail;
import com.justech.eat.repository.OrderDetailRepository;
import com.justech.eat.repository.OrderRepository;
import com.justech.eat.service.OrderBook;
import com.justech.eat.service.event.OrderBookSubmitEvent;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * @program: eat-service
 * @description:
 * @author: feifei.li
 * @create: 2020-05-29 12:17
 **/
@Component(value = "orderBookSave")
public class OrderBookSubmit implements OrderBook {
    @Autowired
    OrderRepository orderRepository;
    @Autowired
    OrderDetailRepository orderDetailRepository;

    @Autowired
    ApplicationContext applicationContext;

    /**
     * 提交报餐
     *
     * @param orderDetailReq
     * @param date
     * @param jobNumber
     * @return
     */
    @Override
    public Order submit(OrderDetailReq orderDetailReq, String date, String jobNumber) {
        Order order = orderRepository.findByDateAndJobNumber(date, jobNumber);
        order = order == null ? save(orderDetailReq, date, jobNumber) : update(order, orderDetailReq, date, jobNumber);
        applicationContext.publishEvent(new OrderBookSubmitEvent(this, order));
        return order;
    }

    @Override
    public void submit(OrderDetailReq orderDetailReq) {

    }

    @Override
    public Order submit(String date, String jobNumber, int lunch, int dinner, int meal, int night) {
        OrderDetailReq o = new OrderDetailReq();
        o.setDate(date);
        o.setJobNumber(jobNumber);
        o.setLunch(lunch);
        o.setDinner(dinner);
        o.setMeal(meal);
        o.setNight(night);
        return submit(o, date, jobNumber);
    }

    @Override
    public Order submit(String date, String jobNumber, OrderDetail... orderDetails) {
        Order order = orderRepository.findByDateAndJobNumber(date, jobNumber);
        if (order == null) {
            order = new Order();
            order.setDate(date);
            order.setDeviceInfo("结算补偿");
            order.setJobNumber(jobNumber);
            order.setCreateTime(new Date());
            order = orderRepository.save(order);
            Map<Integer, OrderDetail> integerOrderDetailMap = listToMap(orderDetails);
            List<OrderDetail> prepareForPersistence = new ArrayList<>(4);
            for (int i = 1; i <= 4; i++) {
                OrderDetail detail = new OrderDetail();
                OrderDetail paramOrderDetail = integerOrderDetailMap.get(i);
                if (paramOrderDetail != null) {
                    detail.setStatus(paramOrderDetail.getResult() != 1 ? 3 : 2);
                    detail.setResult(paramOrderDetail.getResult());
                } else {
                    detail.setStatus(2);
                    detail.setResult(0);
                }
                detail.setType(i);
                detail.setOrderId(order.getId());
                detail.setCreateTime(DateUtil.now());
                detail.setCreateBy("结算补偿");
                prepareForPersistence.add(detail);
            }
            List<OrderDetail> details = orderDetailRepository.saveAll(prepareForPersistence);
            order.setOrderDetails(details);
        }
        return order;
    }

    private Map<Integer, OrderDetail> listToMap(OrderDetail... orderDetails) {
        HashMap<Integer, OrderDetail> hashMap = new HashMap<>();
        for (OrderDetail orderDetail : orderDetails) {
            hashMap.put(orderDetail.getType(), orderDetail);
        }
        return hashMap;
    }


    private Order save(OrderDetailReq req, String date, String jobNumber) {
        if (StringUtils.isBlank(jobNumber)) {
            MesAssert.throwBizException("jobNumber not empty");
        }
        Order order = new Order();
        order.setDate(date);
        order.setDeviceInfo("ios");
        order.setJobNumber(jobNumber);
        order.setCreateTime(new Date());
        order = orderRepository.save(order);

        OrderDetail lunch = new OrderDetail(order.getId(), 1, req.getLunch(), new Date(), "李飞飞");
        OrderDetail dinner = new OrderDetail(order.getId(), 2, req.getDinner(), new Date(), "李飞飞");
        OrderDetail meal = new OrderDetail(order.getId(), 3, req.getMeal(), new Date(), "李飞飞");
        OrderDetail night = new OrderDetail(order.getId(), 4, req.getNight(), new Date(), "李飞飞");

        ArrayList arrayList = new ArrayList<OrderDetail>();
        arrayList.add(lunch);
        arrayList.add(dinner);
        arrayList.add(meal);
        arrayList.add(night);
        List list = orderRepository.saveAll(arrayList);
        order.setOrderDetails(list);
        return order;
    }

    private Order update(Order order, OrderDetailReq orderDetailReq, String date, String jobNumber) {
        Map<Integer, OrderDetail> orderDetailMap = detailMap(order.getOrderDetails());
        orderDetailMap.get(1).setResult(orderDetailReq.getLunch());
        orderDetailMap.get(2).setResult(orderDetailReq.getDinner());
        orderDetailMap.get(3).setResult(orderDetailReq.getMeal());
        orderDetailMap.get(4).setResult(orderDetailReq.getNight());
        Collection<OrderDetail> orderDetails = orderDetailMap.values();
        orderDetailRepository.saveAll(orderDetails);
        return order;
    }

    private Map<Integer, OrderDetail> detailMap(List<OrderDetail> details) {
        HashMap<Integer, OrderDetail> detailHashMap = new HashMap<>(4);
        for (OrderDetail detail : details) {
            detailHashMap.put(detail.getType(), detail);
        }
        return detailHashMap;
    }
}
